package it.polimi.swKnights.SWIMv2.servlets.feedback;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.feedbacks.FeedbackHandlerRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DisputeFeedback
 */
public class DisputeFeedback extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		String username = (String) request.getSession()
				.getAttribute("userName");
		String password = (String) request.getSession()
				.getAttribute("password");

		String feedInterested = username;
		
		String feedbackOwner = request.getParameter("user");
		if (feedbackOwner == null)
		{
			feedbackOwner = feedInterested;
		}

		
		
		String[] idAndGotBy;
		String idFeed;
		String gotBy;
		String feedData;
		try
		{
			feedData = request.getParameter("feed_data");
			idAndGotBy = feedData.split(" @ ");
			idFeed = idAndGotBy[0];
			gotBy = idAndGotBy[1];
		}
		catch (IndexOutOfBoundsException e)
		{

			request.setAttribute("error", Errors.internalconventionerror);
			
			request.setAttribute("curious", feedInterested);
			request.setAttribute("feedOwner", feedbackOwner);
			
			request.getRequestDispatcher("WEB-INF/feedback/SeeFeedbacks.jsp")
					.forward(request, response);
			return;
		}

		FeedbackHandlerRemote feedHand = this
				.lookUp(FeedbackHandlerRemote.class);

		
		
		try
		{
			
			feedHand.disputeFeedback(idFeed, gotBy, username, password);
			

			response.sendRedirect("./seeFeedbacks");
	
		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}

	}

}
